package com.lamda.zhekou.master;

import com.alibaba.fastjson.JSONObject;
import com.lamda.zhekou.ZheKouApplication;
import com.lamda.zhekou.master.session.WorkerSession;
import com.lamda.zhekou.master.session.WorkerSessionScheduler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.log4j.Logger;
import sun.rmi.runtime.Log;

import java.util.UUID;

public class ServerHandler extends SimpleChannelInboundHandler<String> {

    private static Logger LOGGER = Logger.getLogger(ServerHandler.class);

    static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg)
            throws Exception {
     //   LOGGER.info(ctx.channel().remoteAddress() + " Say : " + msg);
        //数据格式： {"hostIp":"worker.ip","timestamp":1440637789785},"route":"vps.register","reqId":1}
        JSONObject jsonObject = JSONObject.parseObject(msg);
        ZheKouApplication.getConfigurableApplicationContext().getBean(WorkerSessionScheduler.class).handler(jsonObject,ctx);
    }

    /*
    * 有新的连接进来
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        channels.add(ctx.channel());


        LOGGER.info(">>>>channelActive: 当前总的channel为:" + this.channels.size());
    }

    /**
     * 有连接断开
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        LOGGER.info(">>>>channelInactive:" + ctx.name());

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        LOGGER.debug(">>>>exceptionCaught, and close ctx");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
            throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state().equals(IdleState.READER_IDLE)) {
                System.out.println("READER_IDLE");
//                ctx.channel().writeAndFlush("");
            } else if (event.state().equals(IdleState.WRITER_IDLE)) {
                System.out.println("WRITER_IDLE");
            } else if (event.state().equals(IdleState.ALL_IDLE)) {
                 LOGGER.error("TCP连接超时,----向客户端发送空串");
                ctx.channel().writeAndFlush("{}\r\n");
                // 超时关闭channel
//                ctx.close();
            }
        }
        super.userEventTriggered(ctx, evt);
    }
}